package com.czk.yygh.msm.controller;

import com.czk.yygh.common.result.Result;
import com.czk.yygh.msm.service.MsmService;
import com.czk.yygh.msm.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/11/22 20:55
 */
@RestController
@RequestMapping("/api/msm")
public class MsmApiController {
    @Resource
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @GetMapping("/send/{phone}")
    public Result sendCode(@PathVariable String phone) {
        // 从redis获取验证码 key-手机号
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok();
        }
        // 整合阿里云短信服务
        // 生成验证码
        code = RandomUtil.getSixBitRandom();
        // 发送短信
        boolean isSend = msmService.send(phone, code);
        // 放入redis
        if (isSend) {
            // 3 分钟过期
            redisTemplate.opsForValue().set(phone, code, 3, TimeUnit.MINUTES);
            return Result.ok();
        }
        return Result.fail().message("发送短信失败");
    }
}
